package com.jp.knowledge.logic;

import android.content.Context;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InviteFriendsModel;
import com.jp.knowledge.util.ResultSubscriber;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/5.
 */

public class InviteFriendsLogic {
	private Context context;
	private String cachePath;
	private FileCacheManager cacheManager;

	public InviteFriendsLogic(Context context){
		this.context = context;
		this.cachePath = context.getCacheDir().getPath() + "/INVITE_FRIEND.DAT";
		this.cacheManager = new FileCacheManager();
	}

	public void getInviteData(){
		HttpHelper.getInstance(context).inviteFriends(new JsonObject(), 0x01, new ResultSubscriber.OnResultListener() {
			@Override
			public void onStart(int requestType) {}
			@Override
			public void onCompleted(int requestType) {}
			@Override
			public void onError(int requestType) {}
			@Override
			public void onNext(IModel data, int requestType) {
				if(data.getErrcode() != 0)
					return;
				final InviteFriendsModel inviteFriendsModel = data.getEntity(InviteFriendsModel.class);
				new Thread(new Runnable() {
					@Override
					public void run() {
						cacheManager.wirteObject(inviteFriendsModel, cachePath);
					}
				}).start();
			}
		});
	}

	public void readInviteData(final ReadDataCallback callback){
		Observable.create(new Observable.OnSubscribe<InviteFriendsModel>() {
			@Override
			public void call(Subscriber<? super InviteFriendsModel> subscriber) {
				InviteFriendsModel data = (InviteFriendsModel) cacheManager.readObject(cachePath);
				subscriber.onNext(data);
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Observer<InviteFriendsModel>() {
			@Override
			public void onCompleted() {}
			@Override
			public void onError(Throwable e) {
				callback.readFinish(null);
			}
			@Override
			public void onNext(InviteFriendsModel data) {
				callback.readFinish(data);
			}
		});
	}

	public interface ReadDataCallback{
		void readFinish(InviteFriendsModel data);
	}
}
